package com.oliver.oliveraiagent.controller;

import cn.hutool.core.util.StrUtil;
import com.oliver.oliveraiagent.common.BaseResponse;
import com.oliver.oliveraiagent.common.ResultUtils;
import com.oliver.oliveraiagent.exception.BusinessException;
import com.oliver.oliveraiagent.exception.ErrorCode;
import com.oliver.oliveraiagent.model.dto.user.UserLoginRequest;
import com.oliver.oliveraiagent.model.dto.user.UserRegisterRequest;
import com.oliver.oliveraiagent.model.vo.UserLoginVO;
import com.oliver.oliveraiagent.service.UserService;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

import static com.oliver.oliveraiagent.constant.UserConstant.USER_LOGIN_STATE;

/**
 * @ClassName UserController
 * @Description TODO
 * @Author snow
 * @Date 2025/5/25 17:10
 **/

@RestController
@RequestMapping("/user")
@Slf4j
public class UserController {

    @Resource
    private UserService userService;

    /**
     * 登录
     * @param loginRequest
     * @param request
     * @return
     */
    @PostMapping("/login")
    public BaseResponse<UserLoginVO> login(@RequestBody UserLoginRequest loginRequest, HttpServletRequest request){
        UserLoginVO userLoginVO = userService.login(loginRequest,request);
        return ResultUtils.success(userLoginVO);
    }

    /**
     * 注册
     * @param registerRequest
     * @return
     */
    @PostMapping("/register")
    public BaseResponse<String> register(@RequestBody UserRegisterRequest registerRequest){
        userService.register(registerRequest);
        return ResultUtils.success("注册成功");
    }

    /**
     * 登出
     * @param request
     * @return
     */
    @GetMapping("/logout")
    public BaseResponse<Boolean> logout(HttpServletRequest request){
        Object user = request.getSession().getAttribute(USER_LOGIN_STATE);
        if (user == null) {
            throw new BusinessException(ErrorCode.NOT_LOGIN_ERROR);
        }
        //  移除用户信息
        request.getSession().removeAttribute(USER_LOGIN_STATE);
        return ResultUtils.success(true);
    }

    /**
     * 上传头像
     * @param file
     * @return
     */
    @PostMapping("/uploadAvatar")
    public BaseResponse<String> uploadAvatar(@RequestParam("file") MultipartFile file) {
        // 校验文件类型
        String fileName = file.getOriginalFilename();
        if (StrUtil.isBlank(fileName)) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"请选择要上传的文件");
        }

        // 校验文件后缀
        String fileSuffix = fileName.substring(fileName.lastIndexOf("."));
        List<String> list = new ArrayList<>();
        list.add(".jpg");
        list.add(".jpeg");
        list.add(".png");
        list.add(".gif");
        if (!list.contains(fileSuffix.toLowerCase())) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"仅支持JPG/PNG/GIF格式图片");
        }

        try {
            // 配置存储路径（建议使用外部存储）
            String storagePath = System.getProperty("user.dir") + "/uploads/avatar";
            File dir = new File(storagePath);
            if (!dir.exists()) {
                dir.mkdirs();
            }

            // 生成唯一文件名
            String uniqueFileName = UUID.randomUUID().toString() + fileSuffix;
            File dest = new File(storagePath + "/" + uniqueFileName);

            // 保存文件
            file.transferTo(dest);

            // 返回访问路径（根据实际部署调整）
            String accessUrl = "/uploads/avatar/" + uniqueFileName;
            return ResultUtils.success(accessUrl);

        } catch (IOException e) {
            log.error("文件上传失败", e);
            throw new BusinessException(ErrorCode.SYSTEM_ERROR,"文件上传失败：" + e.getMessage());
        } catch (Exception e) {
            log.error("未知错误", e);
            throw new BusinessException(ErrorCode.SYSTEM_ERROR,"文件上传失败：" + e.getMessage());
        }
    }

}
